<!--
 * @Author: zhangpeng
 * @Date: 2024-11-22 14:21:56
 * @FilePath: \scientific_research_manager_web\src\views\resultsManagement\components\Vertical\VerticalPerson.vue
 * @LastEditTime: 2024-12-11 10:57:48
 * @Description: 成果 - 纵向项目详情 - 参与人员
-->

<script setup lang="ts">
import { MemberInfoDetailDTO } from '@/types/resultsManagement'
import { getAllPersonListApi } from '@/api/resultsManagement/index'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const props = defineProps({

  /* 是否可编辑 */
  editable: {
    type: Boolean,
    default: false
  },
  /* 人员信息已填写数据 */
  personDataList: {
    type: Array as PropType<MemberInfoDetailDTO[]>,
    default: []
  }
})

/* 查询 人员信息 列表 */
const { runAsync: getAllPersonList, loading: getAllPersonListLoading } = useRequest(getAllPersonListApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response) => {
    if (response) {
      // 可选的人员信息
      const tempList = response.map(person => {
        return {
          accountName: person?.name,
          id: person?.id,
          memberCode: person?.code
        }
      })
      // 之前的校内人员，如果被从系统中删除账号信息，则在此处塞入可选的人员信息中，兼容被删除之前就创建的详情数据
      const oldDeletedPersonList = tableData.value.map((personInfo: any) => {
        if (personInfo.type === 1 && tempList.filter(item => item.id === personInfo.accountId).length === 0) {
          return personInfo
        } else {
          return undefined
        }
      }).filter(item => item !== undefined)
      originalOptionPersonList.value = [...oldDeletedPersonList, ...tempList]
      nextTick(() => {
        optionPersonList.value = originalOptionPersonList.value
      })
    }
  },
  // 请求失败
  onError: () => {
  },
})

// 表单引用
const tableForm = ref()
// 校验表单数据
const tableData = ref<MemberInfoDetailDTO[]>([])

// 人员类型
const memberTypeList = ref([
  {
    title: "校内人员",
    value: 0,
  }, {
    title: "校外人员",
    value: 1,
  }
])

watch(() => [props.personDataList, props.editable], () => {
  try {
    tableData.value = JSON.parse(JSON.stringify(props.personDataList)).map((i => {
      if (i?.memberType === 1) {
        return { ...i, accountId: i?.accountName }
      } else {
        return i
      }
    }))

    nextTick(() => {
      if (!tableData.value?.length && props.editable) { //  新增默认添加当前用户为第一条数据
        tableData.value = [{
          accountId: userStore.id,  //  校外姓名 / 校内id
          memberCode: userStore.code,  //  工号,
          memberType: 0,  //  类型
          accountName: userStore.name
        }]
      }
    })
  } catch {
    tableData.value = []
  }

  getAllPersonList({ inside: 1 })
}, { immediate: true })

const originalOptionPersonList = ref([
  // {
  //   accountName: "教师1",
  //   id: '45646786453',
  //   memberCode: '21.35213'
  // }, {
  //   accountName: "教师2",
  //   id: '23351323',
  //   memberCode: 'sdsfs'
  // }
])

// 可选的人员信息
const optionPersonList = ref()

const tempData = {
  accountId: undefined,  //  校外姓名 / 校内id
  memberCode: undefined,  //  工号,
  memberType: undefined,  //  类型
}


const scopeTypeChange = (record) => {
  record.accountId = ''
  if (record?.memberType === 1) {
    record.memberCode = '-'
  } else {
    record.memberCode = ''
  }
}

const scopePersonChange = (record) => {
  const selPer = optionPersonList?.value?.filter((i) => record?.accountId === i?.id)[0]
  record.memberCode = selPer?.memberCode
  record.accountName = selPer?.accountName
}


// 新增角色
const addRole = () => {
  tableData.value.push(JSON.parse(JSON.stringify(tempData)))
}

// 人员信息 >> 按姓名和工号搜索
const customFilterMethod = (searchKey: string) => {
  if (searchKey !== '') {
    nextTick(() => {
      optionPersonList.value = originalOptionPersonList.value.filter((person: any) => { return person.accountName.includes(searchKey) || person.memberCode.includes(searchKey) })
    })
  } else {
    optionPersonList.value = originalOptionPersonList.value
  }
}


// 删除一行人员信息数据
const deleteRowPersonInfo = (rowIndex: number) => {
  tableData.value.splice(rowIndex, 1)
}



// 表单校验
const checkTableFormValidate = (callback: Function) => {
  tableForm.value?.validate().then(() => {
    callback()
  }).catch((err) => {
    callback(err)
  })
}


onMounted(() => {

})

const exposeData = computed(() => {
  let data = tableData.value?.map((i: MemberInfoDetailDTO) => {
    if (i.memberType === 0) {
      return {
        type: i.memberType,
        accountId: i.accountId,
        name: i.accountName,
        code: i.memberCode,
      }
    } else {
      return {
        type: i.memberType,
        name: i.accountId,
        code: i.memberCode,
      }
    }
  })
  return data
})

defineExpose({
  checkTableFormValidate,
  exposeData,
})
</script>

<template>
  <div class="apply-record" style="padding-bottom: 24px;">
    <div class="area-title">
      参与者
      <el-button v-if="props.editable && tableData?.length < 20" type="primary" style="margin-top: -6px;"
        @click="addRole" :disabled="tableData?.length >= 20">新增人员</el-button>
    </div>
    <div>
      <el-form ref="tableForm" :model="tableData">
        <el-table :data="tableData" :auto-height="true" border>
          <el-table-column type="index" label="序号" width="46" />

          <el-table-column props="memberType" label="类型">
            <template #default="scope">
              <div v-if="props.editable" class="py-[8px]">
                <el-form-item :prop="`[${scope.$index}].memberType`" label-width="0px" validate="change"
                  :rules="{ required: true, message: '类型不能为空', trigger: 'change' }">
                  <el-select v-model="scope.row.memberType" placeholder="请选择" clearable
                    @change="scopeTypeChange(scope?.row)">
                    <el-option v-for="option in memberTypeList" :key="option.value" :label="option.title"
                      :value="option.value" />
                  </el-select>
                </el-form-item>
              </div>


              <span v-else>{{ scope.row.memberType === 0 ? '校内人员' : '校外人员' }}</span>
            </template>
          </el-table-column>

          <el-table-column props="accountId" label="姓名">
            <template #default="scope">
              <div v-if="props.editable"  class="py-[8px]">
                <el-form-item :prop="`[${scope.$index}].accountId`" label-width="0px" validate="change"
                  :rules="{ required: true, message: '姓名不能为空', trigger: 'change' }">
                  <el-select v-if="scope.row.memberType === 0" v-model="scope.row.accountId" placeholder="请选择"
                    filterable clearable :filter-method="customFilterMethod" @change="scopePersonChange(scope?.row)">
                    <el-option v-for="option in optionPersonList" :key="option.id" :label="option.accountName"
                      :disabled="tableData?.filter((i) => i.accountId === option.id)?.length > 0" :value="option.id" />
                  </el-select>
                  <el-input v-else v-model="scope.row.accountId"></el-input>
                </el-form-item>
              </div>

              <span v-else>{{ scope.row.accountName }}</span>
            </template>
          </el-table-column>

          <el-table-column props="memberCode" label="工号">
            <template #default="scope">
              <span>{{ scope?.row?.memberCode }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="270" v-if="props.editable">
            <template #default="scope">
              <el-button v-if="tableData.length > 1" type="danger" link @click="deleteRowPersonInfo(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>

        </el-table>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.apply-record {
  display: flex;
  flex-direction: column;
  height: auto;
  background-color: white;
  padding-left: 20px;
  padding-right: 20px;

  .area-title {
    height: 20px;
    font-weight: bold;
    color: #1D2129;
    font-size: 14px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;

    :deep(.el-button) {
      height: 32px;
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 0px;
  }

  :deep(.el-table .cell) {
    overflow: visible;
  }
}
</style>